﻿using Autofac;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Cyss.Core.Api
{
    /// <summary>
    /// 消息上下文,记录当前http请求中所有的消息(此方法http程序(web,api wcf 等) 不能用于 winform 程序)
    /// </summary>
    public class MessageContext : IMessageContext
    {
        private MessageService messageService;
        public MessageContext()
        {
            messageService = new MessageService();
        }

        /// <summary>
        /// 添加上下文消息
        /// </summary>
        /// <param name="Content"></param>
        /// <param name="Title"></param>
        public void InsertMessage(string Content, string Title = "")
        {
            messageService.InsertMessage(Content, Title);
        }

        /// <summary>
        /// 获取上下文消息
        /// </summary>
        /// <returns></returns>
        public string GetMessage(bool IsClear = false)
        {
            return messageService.GetMessage(IsClear);
        }

        /// <summary>
        /// 获取上下文消息集合
        /// </summary>
        /// <returns></returns>
        public IList<MessageFactoryModel> GetMessages()
        {
            return messageService.messageFactoryModels;
        }
    }

    /// <summary>
    /// 消息服务
    /// </summary>
    internal class MessageService
    {
        public List<MessageFactoryModel> messageFactoryModels;

        public MessageService()
        {
            messageFactoryModels = new List<MessageFactoryModel>();
        }

        public void InsertMessage(string Content, string Title = "")
        {
            if (messageFactoryModels == null)
            {
                messageFactoryModels = new List<MessageFactoryModel>();
            }
            messageFactoryModels.Add(new MessageFactoryModel { Content = Content, Title = Title });
        }

        /// <summary>
        /// 获取消息字符串
        /// </summary>
        /// <returns></returns>
        public string GetMessage(bool IsClear = false)
        {
            if (messageFactoryModels == null)
            {
                messageFactoryModels = new List<MessageFactoryModel>();
            }
            StringBuilder stringBuilder = new StringBuilder();
            messageFactoryModels.ForEach(x =>
            {
                stringBuilder.Append($"{x.Title} {x.Content}" + Environment.NewLine);
            });
            if (IsClear) messageFactoryModels.Clear();
            return stringBuilder.ToString();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            StringBuilder stringBuilder = new StringBuilder();
            messageFactoryModels.ForEach(x =>
            {
                stringBuilder.Append($"{x.Title} {x.Content}" + Environment.NewLine);
            });
            return stringBuilder.ToString();
        }
    }



}
